package edu.scu.lijobs.android;


import static edu.scu.lijobs.android.GCMManager.DISPLAY_MESSAGE_ACTION;
import static edu.scu.lijobs.android.GCMManager.EXTRA_MESSAGE;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;

import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.google.code.linkedinapi.client.JobsApiClient;
import com.google.code.linkedinapi.client.JobsApiClient.JobBuilder;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.Parameter;
import com.google.code.linkedinapi.client.enumeration.JobField;
import com.google.code.linkedinapi.client.enumeration.SearchParameter;
import com.google.code.linkedinapi.client.enumeration.SearchSortOrder;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.FacetType;
import com.google.code.linkedinapi.schema.Job;
import com.google.code.linkedinapi.schema.JobFunctionCode;
import com.google.code.linkedinapi.schema.Jobs;
import com.google.code.linkedinapi.schema.Person;

import edu.scu.lijobs.android.R;

public class LIMainActivity extends Activity {
    
	
	public static final String CONSUMER_KEY = "45vjs1mpz5il";
	public static final String CONSUMER_SECRET = "03yYik0uZ7lHkWfS";
	

		AsyncTask<Void, Void, Void> mRegisterTask;
	
	
	//public static final String CONSUMER_SECRET = "WwJxhr93mYGLOpN3";

	
	
	public static final String APP_NAME = "Jobs@Linkedin";
    public static final String OAUTH_CALLBACK_SCHEME    = "x-oauthflow-linkedin";
    public static final String OAUTH_CALLBACK_HOST      = "lijobscallback";
    public static final String OAUTH_CALLBACK_URL       = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
   
    
    
    
    static final String OAUTH_QUERY_TOKEN               = "oauth_token";
    static final String OAUTH_QUERY_VERIFIER            = "oauth_verifier";
    static final String OAUTH_QUERY_PROBLEM             = "oauth_problem";
    static final String OAUTH_PREF                      = "AppPreferences";
    static final String PREF_TOKEN                      = "linkedin_token";
    static final String PREF_TOKENSECRET                = "linkedin_token_secret";
    static final String PREF_REQTOKENSECRET             = "linkedin_request_token_secret";

    LinkedInOAuthService oAuthService             = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET);
    LinkedInApiClientFactory factory              = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
    LinkedInRequestToken liToken;
    LinkedInApiClient client;

    TextView tv = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    	//CookieSyncManager.createInstance(this);
    	//CookieManager cookieManager = CookieManager.getInstance();
    	//cookieManager.removeAllCookie();
        
        tv = new TextView(this);
        setContentView(tv);
        final SharedPreferences pref    = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
        final String token              = pref.getString(PREF_TOKEN, null);
        final String tokenSecret        = pref.getString(PREF_TOKENSECRET, null);
        
        
        if (token == null || tokenSecret == null) {
            startAutheniticate();
        } else {
        	 LinkedInApiManager.LINKED_IN_ACCESS_TOKEN = new LinkedInAccessToken(token, tokenSecret);
             
     
        	 
        	Intent i=new Intent(LIMainActivity.this,TabsViewPagerFragmentActivity.class);
            startActivity(i);
            startGCM();
            
     
        }
        UiHelper.liMainActivity = this;
    }//end method
    
    
    
    

    
    private void startGCM() {
    	checkNotNull(GCMManager.SERVER_URL, "SERVER_URL");
        checkNotNull(GCMManager.SENDER_ID, "SENDER_ID");
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
        
      
       registerReceiver(mHandleMessageReceiver,
                new IntentFilter(DISPLAY_MESSAGE_ACTION));
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, GCMManager.SENDER_ID);
        } else {
        	GCMManager.REG_ID = regId;
            // Device is already registered on GCM, check server.
//            if (GCMRegistrar.isRegisteredOnServer(this)) {
//                // Skips registration.
//            	final Context context = this;
//                mDisplay.append(getString(R.string.already_registered) + "\n");
//            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered =
                                ServerUtilities.register(context, regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
    }
    void startAutheniticate() {
        new Thread(){//added because this will make code work on post API 10 
            @Override
            public void run(){  
                final LinkedInRequestToken liToken  = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL); 
                final String uri                    = liToken.getAuthorizationUrl();
                final SharedPreferences pref        = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
                SharedPreferences.Editor editor     = pref.edit(); 
                editor.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret());
                editor.commit();
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(i);
             }
        }.start();
    }//end method

    void finishAuthenticate(final Uri uri) {
    	
    	
    	 Intent i=new Intent(LIMainActivity.this,TabsViewPagerFragmentActivity.class);
         startActivity(i);
         
        new Thread(){
            @Override
            public void run(){
                Looper.prepare();
                if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
                    final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
                    if (problem == null) {
                        final SharedPreferences pref                = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE);
                        final String request_token_secret           = pref.getString(PREF_REQTOKENSECRET, null);
                        final String query_token                    = uri.getQueryParameter(OAUTH_QUERY_TOKEN);
                        final LinkedInRequestToken request_token    = new LinkedInRequestToken(query_token, request_token_secret);
                        final LinkedInAccessToken accessToken       = oAuthService.getOAuthAccessToken(request_token, uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
                        SharedPreferences.Editor editor = pref.edit(); 
                        editor.putString(PREF_TOKEN, accessToken.getToken());
                        editor.putString(PREF_TOKENSECRET, accessToken.getTokenSecret());
                        editor.remove(PREF_REQTOKENSECRET);
                        editor.commit();
                        LinkedInApiManager.LINKED_IN_ACCESS_TOKEN = accessToken;
                        startGCM();
//                        showCurrentUser(accessToken);
                    } else {
                        Toast.makeText(getApplicationContext(), "Application down due OAuth problem: " + problem, Toast.LENGTH_LONG).show();
                        finish();
                    }
                }
                Looper.loop();
            }
        }.start();
    }//end method

    void clearTokens() {
        getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit().remove(PREF_TOKEN).remove(PREF_TOKENSECRET).remove(PREF_REQTOKENSECRET).commit();
    }//end method

    void showCurrentUser(final LinkedInAccessToken accessToken) {
        new Thread(){
            @Override
            public void run(){
                Looper.prepare();
                final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken);
                try {
                    final Person p = client.getProfileForCurrentUser();
                    // /////////////////////////////////////////////////////////
                    // here you can do client API calls ...
                    // client.postComment(arg0, arg1);
                    // client.updateCurrentStatus(arg0);
                    // or any other API call (this sample only check for current user
                    // and shows it in TextView)
                    // /////////////////////////////////////////////////////////             
                    runOnUiThread(new Runnable() {//updating UI thread from different thread not a good idea...
                        public void run() {
                            tv.setText(p.getLastName() + ", " + p.getFirstName());
                        }
                    });
                    //or use Toast
                    //Toast.makeText(getApplicationContext(), "Lastname:: "+p.getLastName() + ", First name: " + p.getFirstName(), 1).show();
                } catch (LinkedInApiClientException ex) {
                    clearTokens();
                    Toast.makeText(getApplicationContext(),
                        "Application down due LinkedInApiClientException: "+ ex.getMessage() + " Authokens cleared - try run application again.",
                        Toast.LENGTH_LONG).show();
                    finish();
                }
                Looper.loop();
            }
        }.start();
    }//end method

    @Override
    protected void onNewIntent(Intent intent) {
        finishAuthenticate(intent.getData());
    }//end method
    
    
    
    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        unregisterReceiver(mHandleMessageReceiver);
        GCMRegistrar.onDestroy(this);
        super.onDestroy();
    }
    
  


    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }

    
	
	
	
	 private final BroadcastReceiver mHandleMessageReceiver =
	            new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
	            System.out.println("NEW MESSAGE");
	          
	        }
	    };
}//end class